<!DOCTYPE html>
<html lang="en">
	<head>
		<title>展示</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<meta name="viewport" content="width=device-width; initial-scale=1.0">
		<meta name="viewport"
			content="height=device-height, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
		<link rel="stylesheet" type="text/css" href="./css/index.css" />
	</head>
	<body>
		<div id="em">
			<div id="info">
				<div class="loading" v-if="!showLeft">
					<div class="loader"></div>
					<div class="loading-text" v-html="`3D模型正在加载中...(${percentage})`"></div>
				</div>
			</div>
			<div v-if="showLeft">
				<div class="leftBox-topInit" v-show="isShowNum==0">
					<img class="leftBox-tapImg" src="./img/icon-zhan1.png" style="float:right" @click="setShow(1)">
				</div>

				<div v-show="isShowNum==1">
					<div class="leftBox">
						<div class="leftBox-tap">
							<img class="leftBox-tapImg" src="./img/icon-zhan.png"
								style="position: relative;left: 180px;" @click="setShow(0)">
							<!-- <img class="leftBox-tapImg" src="./img/icon-close.png" @click="goBack()"> -->
						</div>
						<div class="screenBox">
							<div class="screenBoxTitle">设备健康情况</div>
							<div class="screenBoxCenter">
								<div class="screenBoxCenterItem">
									<div class="screenBoxCenterItem-dian bg1"></div>
									<div class="screenBoxCenterItem-name">正常</div>
									<div class="screenBoxCenterItem-num" v-html="lineStatus.normal">11</div>
								</div>
								<div class="screenBoxCenterItem">
									<div class="screenBoxCenterItem-dian bg4"></div>
									<div class="screenBoxCenterItem-name">异常</div>
									<div class="screenBoxCenterItem-num" v-html="lineStatus.unusual">22</div>
								</div>
							</div>
						</div>
						<div class="leftBox-tap2" @click="openPopupLeft()">
							<span v-html="wholeLine"></span>
							<img class="leftBox-tapImg" src="./img/jiantou.png">
						</div>
						<ul class="popupLeftBox" v-if="isShowPopupLeft">
							<li class="popupLeftBoxItem" @click="selectLine(item)" v-for="(item,index) in lineList"
								:key="item.id">{{item.name}}</li>
						</ul>
						<ul class="box-left" id="parent">
							<li style="position: relative;" v-for="(item,i) in showDataJson" :key="i" :id="'child'+i">
								<div class="parts" :class="item.showColor==true?'parts-cur':''"
									:style="{backgroundColor:item.alarmLevel==1?'#AB8D15':item.alarmLevel==2?'#995D12':item.alarmLevel==3?'#80232E':''}"
									:key="item.id" @click="setHighlight(i,item.unitId,item.typeId,0)"
									v-html="item.name">
								</div>
							</li>
						</ul>
					</div>
				</div>
				<div class="box-right">
					<div class="box-right-title">智能分析</div>
					<div class="box-right-desc" v-html="desc?desc:'暂无分析'"></div>
					<div class="Boxbotton" v-if="unitId" @click="againPost()">点击查看设备</div>
				</div>
			</div>
		</div>
	</body>
	<script src="./js/vue.js"></script>
	<script type="text/javascript" src="js/uni.webview.1.5.2.js"></script>
	<script src="./js/three/three.js"></script>
	<script src="./js/three/loaders/STLLoader.js"></script>
	<script src="./js/three/Detector.js"></script>
	<script src="./js/three/controls/OrbitControls.js"></script>
	<script src="./js/three/libs/stats.min.js"></script>
	<script src="./js/md5.js"></script>
	<!-- 引入axios -->
	<script src="./js/axios.js"></script>
	<script>
		if (!Detector.webgl) Detector.addGetWebGLMessage();
		// var container = document.createElement( 'div' );
		var container;
		var times;
		var stats = new Stats();
		var raycaster = new THREE.Raycaster();
		var mouse = new THREE.Vector2();
		var group = new THREE.Group();
		var loader = new THREE.STLLoader();
		var daColor, previous = null,
			cnt = 0;
		// var AllLineArr = [],
		// 	line, lineW1 = 0,
		// 	lineW2 = 0;
		var camera, cameraTarget, scene, renderer;
		var quanju = [];
		var width = window.innerWidth;
		var height = window.innerHeight;
		var app = new Vue({
			el: '#em',
			data: {
				dataJson: [],
				showDataJson: [],
				unitId: '',
				typeId: '',
				entId: '',
				showLeft: false,
				url: '',
				imgUrl: '',
				percentage: '0%',
				clickIndex: null,
				desc: '',
				lineId: '', //整线id
				isShowNum: 1, //是否显示左边内容
				isShowPopupLeft: false, //是否显示左边弹出框
				isShowPopupRight: false, //是否显示右边弹出框
				wholeLine: '', //整线名字
				lineStatus: {}, //整线状态
				lineList: [], //整线列表
				clickTimetype: false
			},
			created() {
				this.unitId = getParamValue('unitId')
				this.lineId = getParamValue('lineId')
				this.typeId = getParamValue('typeId')
				this.entId = getParamValue('entId')
				this.url = getParamValue('url')
				this.imgUrl = getParamValue('imgUrl')
				//判断lineId不为空则为整线
				//获取整线状态
				this.getLineTotal();
				//获取整线列表
				this.getLineList();
				this.getDataOrder();
			},
			computed: {
				// activeUsers: function() {
				// 	return this.dataJson.filter(function(item) {
				// 		return item.button == 1
				// 	})
				// }
			},
			methods: {
				//查看设备
				againPost() {
					this.isShowPopupRight = false;
					this.isShowPopupLeft = false;
					window.parent.postMessage({
						data: {
							unitId: this.unitId,
							typeId: this.typeId,
							type: 1
						}
					})
				},
				//后退
				goBack() {
					uni.navigateBack({
						delta: 1
					});
				},
				//展开收起左侧
				setShow(e) {
					this.isShowNum = e;
				},
				//打开整线列表
				openPopupLeft() {
					this.isShowPopupLeft = !this.isShowPopupLeft
				},
				//选择整线
				selectLine(item) {
					this.isShowPopupLeft = false;
					this.lineId = item.lineId;
					this.typeId = item.typeId;
					this.wholeLine = item.name;
					this.getLineTotal();
					this.getDataOrder();
				},
				//选择测点
				selectPoint() {
					this.isShowPopupRight = false;
				},
				setColor(color) {
					return Number('0x' + color)
				},
				setView() {
					this.dataJson.forEach((item, i) => {
						item.stlFile = this.imgUrl + item.stlFile;
						item.showColor = false;
						item.color = this.setColor(item.color);
						loaderFile(item, i, this.dataJson.length).then((data) => {
							this.percentage = data.sum;
							if (data.type) {
								this.showLeft = true;
							}
						})
					})
					this.dynamic(0)
				},
				getDataOrder() {
					let _this = this;
					let url = _this.url + '/backend-api/app/model/line/get';
					let token = getParamValue('token')
					let header1 = getHeaderJson(token)
					let header2 = {
						"Content-Type": 'application/x-www-form-urlencoded'
					}
					let param = {};
					param.lineId = this.lineId
					param.typeId = this.typeId

					axios({
						headers: Object.assign(header1, header2),
						method: 'get',
						url: url,
						params: param
					}).then(function(response) {
						if (response.data.code === 1000) {
							_this.dataJson = response.data.data;
							let arr = []
							_this.dataJson.forEach(item => {
								if (item.button == 1) {
									arr.push(item)
								}
							})
							_this.showDataJson = arr;
							_this.setView()
						}
					}).catch(function(error) {
						console.log(error)
						// plus.nativeUI.toast("加载模型失败")
					})
				},

				//获取整线设备状态
				getLineTotal() {
					let _this = this;
					let url = _this.url + '/backend-api/app/line/total';
					let token = getParamValue('token')
					let header1 = getHeaderJson(token)
					let header2 = {
						"Content-Type": 'application/x-www-form-urlencoded'
					}
					let obj = {
						line_id: this.lineId
					};
					axios({
						headers: Object.assign(header1, header2),
						method: 'get',
						url: url,
						params: obj
					}).then(function(response) {
						if (response.data.code === 1000) {
							_this.lineStatus = response.data.data;
						}
					}).catch(function(error) {
						console.log(error)
						// plus.nativeUI.toast("加载模型失败")
					})
				},
				//获取整线列表
				getLineList() {
					let _this = this;
					let url = _this.url + '/backend-api/web/monitor/lines';
					let token = getParamValue('token')
					let header1 = getHeaderJson(token)
					let header2 = {
						"Content-Type": 'application/x-www-form-urlencoded'
					}
					let obj = {
						entId: this.entId
					};
					axios({
						headers: Object.assign(header1, header2),
						method: 'get',
						url: url,
						params: obj
					}).then(function(response) {
						if (response.data.code === 1000) {
							_this.lineList = response.data.data;
							_this.lineList.forEach(item => {
								if (_this.lineId == item.line_id) {
									_this.wholeLine = item.name
								}
							})
						}
					}).catch(function(error) {
						console.log(error)
						// plus.nativeUI.toast("加载模型失败")
					})
				},
				//定时器
				dynamic(e) {
					let _this = this;
					let a = e;
					times = setInterval(function() {
						_this.setHighlight(a, _this.showDataJson[a].unitId, _this.showDataJson[a].typeId, 1)
						if (a < _this.showDataJson.length - 1) {
							a++
						} else {
							a = 0;
						}
						scrollto(a)
					}, 2000)

					// times()
				},

				setHighlight(i, unitId, typeId, y) {
					let _this = this;
					if (y == 0) {
						clearInterval(times)
						//拦截一下10秒钟内多次点击触发的定时器，10秒内只触发一次
						if (!this.clickTimetype) {
							this.clickTimetype = true;
							setTimeout(() => {
								_this.clickTimetype = false;
								_this.dynamic(i)
							}, 10000)
						}
					}
					this.desc = this.showDataJson[i].alarmDesc;
					this.unitId = unitId;
					this.typeId = typeId;
					let Acolor = daColor;
					let indexn;
					this.dataJson.forEach((item, n) => {
						if (item.unitId == this.showDataJson[i].unitId) {
							indexn = n
						}
					})
					if (this.clickIndex == i) {
						this.showDataJson[i].showColor = false;
						quanju[indexn].material.color.set(Acolor);
						this.clickIndex = null
						app.$forceUpdate();
						return
					}
					this.clickIndex = i;
					this.showDataJson.forEach((item, b) => {
						if (i == b) {
							item.showColor = true;
						} else {
							item.showColor = false;
						}
					})
					app.$forceUpdate();
					if (previous == i) {
						quanju[previous].material.color.set(Acolor);
						return
					}
					daColor = quanju[indexn].material.color.getHex()
					quanju[indexn].material.color.set(0x2894FF);

					if (previous != null) {
						quanju[previous].material.color.set(Acolor);
					}
					previous = indexn;
				},

			}
		})

		function scrollto(e) {
			// 获取父盒子（肯定有滚动条）
			var parent = document.getElementById('parent');
			parent.scrollTop = document.getElementById('child' + e).offsetTop - document.getElementById('child' + e)
				.offsetHeight
		}

		//分解url获得数据部分
		function getUrlParams() {
			var search = window.location.search;
			// 写入数据字典 
			var tmparray = search.substr(1, search.length).split("&");
			var paramsArray = new Array;
			if (tmparray != null) {
				for (var i = 0; i < tmparray.length; i++) {
					var reg = /[=|^==]/; // 用=进行拆分，但不包括== 
					var set1 = tmparray[i].replace(reg, '&');
					var tmpStr2 = set1.split('&');
					var array = new Array;
					array[tmpStr2[0]] = tmpStr2[1];
					paramsArray.push(array);
				}
			}
			// 将参数数组进行返回 
			return paramsArray;
		}

		// 根据参数名称获取参数值 
		function getParamValue(name) {
			var paramsArray = getUrlParams();
			if (paramsArray != null) {
				for (var i = 0; i < paramsArray.length; i++) {
					for (var j in paramsArray[i]) {
						if (j == name) {
							return paramsArray[i][j];
						}
					}
				}
			}
			return null;
		}
		init();

		function init() {
			container = document.getElementById('info')
			// document.body.appendChild(container);
			//创建场景
			scene = new THREE.Scene();
			scene.background = new THREE.Color(0x000B17);
			scene.fog = new THREE.Fog(0x000B17, 2, 15);


			// var plane = new THREE.Mesh(
			// 	new THREE.PlaneBufferGeometry(40, 40),
			// 	new THREE.MeshPhongMaterial({
			// 		color: 0x999999,
			// 		specular: 0x101010
			// 	})
			// );
			// plane.rotation.x = 0;
			// plane.position.y = 0;
			// scene.add(plane);

			// plane.receiveShadow = true;


			// 灯光
			var light = new THREE.HemisphereLight(0xefefff, 0x111122, 1)
			scene.add(light);
			// addShadowedLight(1, 1, 1, 0xefefff, 1.35);
			// addShadowedLight(0.5, 1, -1, 0xeaeaea, 1);


			// var light = new THREE.DirectionalLight(0xefefff, 1.5);
			// light.position.set(1, 1, 1).normalize();
			// scene.add(light);

			// var light = new THREE.DirectionalLight(0xffefef, 1.5);
			// light.position.set(-1, -1, -1).normalize();
			// scene.add(light);


			//创建渲染器
			renderer = new THREE.WebGLRenderer({
				antialias: true,
				alpha: true
			});
			renderer.setPixelRatio(window.devicePixelRatio);
			renderer.setSize(width, height);

			renderer.gammaInput = true;
			renderer.gammaOutput = true;

			renderer.shadowMap.enabled = true;

			container.appendChild(renderer.domElement);

			//相机   透视投影照相机 /* 四个参数分别表示：多少度视角，相机的宽高比，最近距离，最远可视距离*/
			camera = new THREE.PerspectiveCamera(45, width / height, 0.005, 1500);

			// camera.position.set(0, -2, 3);
			camera.position.set(0, 0, 5);




			cameraTarget = new THREE.Vector3(0, 0, 0);
			// stats
			// stats.domElement.style.left = '50px';
			// container.appendChild(stats.dom);

			// initObject(0, 0, 0);
			//加入事件监听器,窗口自适应
			window.addEventListener('resize', onWindowResize, false);
			// document.addEventListener('click', onMouseClick,true);
		}

		function loaderFile(item, i, length) {
			// console.log(item.stlFile)
			return new Promise((resolve, reject) => {
				loader.load(item.stlFile, function(geometry) {
					var material = new THREE.MeshPhongMaterial({
						color: item.color,
						transparent: item.transparent == 1 ? true : false,
						opacity: item.opacity, // 定义物体的透明度。与 transparent 属性一起使用。该属性的赋值范围从 0 到 1。
						visible: true, //定义该材质是否可见。如果设置为 false,那么在场景中就看不到该物体。
						depthTest: true, //遮挡
						// side: THREE.DoubleSide, 
						// depthWrite: false


					});
					quanju[i] = new THREE.Mesh(geometry, material);
					quanju[i].position.set(item.pointX, item.pointY, item.pointZ);
					quanju[i].rotation.set(item.rotaX, item.rotaY, item.rotaZ);
					quanju[i].scale.set(item.scaleX, item.scaleY, item.scaleZ);
					quanju[i].rotateStatus = item.rotateStatus;
					quanju[i].rotateSpeed = item.rotateSpeed;
					quanju[i].rotateShaft = item.rotateShaft;
					scene.add(quanju[i]);
					cnt += 1; //加载成功数+1
					let sum = Math.round((cnt / length) * 100) + '%'

					if (cnt >= length) { //全部加载完
						requestAnimationFrame(render);
						resolve({
							type: true,
							sum: sum
						});
						reject(false);
					} else {
						resolve({
							sum: sum
						});
					}
				});
			})

		}

		function addShadowedLight(x, y, z, color, intensity) {

			var directionalLight = new THREE.DirectionalLight(color, intensity);
			directionalLight.position.set(x, y, z);
			scene.add(directionalLight);

			directionalLight.castShadow = true;

			var d = 1;
			directionalLight.shadow.camera.left = -d;
			directionalLight.shadow.camera.right = d;
			directionalLight.shadow.camera.top = d;
			directionalLight.shadow.camera.bottom = -d;

			directionalLight.shadow.camera.near = 1;
			directionalLight.shadow.camera.far = 4;

			directionalLight.shadow.mapSize.width = 1024;
			directionalLight.shadow.mapSize.height = 1024;

			directionalLight.shadow.bias = -0.002;

		}
		//可视窗口重置
		function onWindowResize() {
			//加入事件监听器,窗口自适应
			camera.aspect = width / height;
			camera.updateProjectionMatrix();

			renderer.setSize(width, height);

		}


		//绘画渲染
		function render() {

			// camera.lookAt(cameraTarget);
			// stats.update(); //更新当前统计

			renderer.render(scene, camera);
			requestAnimationFrame(animation); //请求再次执行渲染函数animation

		}
		//动画库
		function animation() {
			quanju.forEach((item) => {
				if (item.rotateStatus == 1) {
					switch (item.rotateShaft) {
						case 'X':
							item.rotateX(item.rotateSpeed)
							break
						case 'Y':
							item.rotateY(item.rotateSpeed)
							break
						case 'Z':
							item.rotateZ(item.rotateSpeed)
							break
					}
				}
			})
			// repeat()
			render()
		}

		//点击事件
		function onMouseClick(event) {

			//将鼠标点击位置的屏幕坐标转换成threejs中的标准坐标

			mouse.x = (event.clientX / window.innerWidth) * 2 - 1
			mouse.y = (event.clientY / window.innerHeight) * 2 + 1

			// 		// 通过鼠标点的位置和当前相机的矩阵计算出raycaster
			// 		raycaster.setFromCamera(mouse, camera);
			// 		// 获取raycaster直线和所有模型相交的数组集合
			// 		var intersects = raycaster.intersectObjects(scene.children);

			// 		//将所有的相交的模型的颜色设置为红色
			// 		for (var i = 0; i < intersects.length; i++) {

			// 			intersects[i].object.material.color.set(0xff0000);
			// 		}
		}



		/**
		 * @description 初始化添加物体,画一条线
		 */
		// function initObject(e, q, type) {
		// 	let color
		// 	if (type == 0) {
		// 		color = 0xff0000;
		// 	} else {
		// 		color = 0xc0c0c0;
		// 	}
		// 	let material = new THREE.LineBasicMaterial({
		// 		color: color
		// 	});
		// 	let geometry = new THREE.Geometry();
		// 	geometry.vertices.push(
		// 		new THREE.Vector3(q, 0.01, 0), new THREE.Vector3(e, 0.01, 0)
		// 	);
		// 	line = new THREE.Line(geometry, material);
		// 	line.position.x = -6.5145408
		// 	scene.add(line)
		// 	AllLineArr.push(line)
		// }
		// //循环显示过钢
		// function repeat() {
		// 	if (lineW2 < 9) {
		// 		lineW2 += 0.05
		// 		initObject(lineW2, 0, 0);
		// 		return
		// 	} else {
		// 		if (lineW1 < 9) {
		// 			lineW1 += 0.05
		// 			initObject(lineW1, 0, 1);

		// 		} else {
		// 			if (AllLineArr.length > 0) {
		// 				scene.remove(AllLineArr[0]);
		// 				AllLineArr.shift()
		// 			} else {
		// 				// lineW2 = 0;
		// 				// lineW1 = 0;
		// 				// repeat()
		// 			}
		// 		}
		// 	}
		// }
		//轨道控制 镜头的移动
		var controls = new THREE.OrbitControls(camera, renderer.domElement); //创建控件对象
	</script>
</html>
